import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Space,
  message,
  Card,
  Tag,
  Descriptions,
  Spin,
} from "antd";
import { EyeOutlined, EditOutlined, CrownOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { AdminControllerService } from "../api";
import type { VidUser_ } from "../api";

interface UserData {
  id?: string;
  nickName?: string;
  phoneNumber?: string;
  vipStatus?: boolean;
  expiredDate?: string;
  createdTime?: string;
  updatedTime?: string;
}

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<UserData[]>([]);
  const [isViewModalVisible, setIsViewModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [selectedUser, setSelectedUser] = useState<UserData | null>(null);
  const [searchParams, setSearchParams] = useState<any>({});
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 加载用户列表
  const loadUsers = async (current = 1, size = 10, params?: any) => {
    try {
      setTableLoading(true);
      const response = (await AdminControllerService.userListUsingGet(
        current,
        size,
        undefined, // createdTime
        undefined, // expiredDate
        params?.nickName,
        params?.phoneNumber,
        params?.vipStatus
      )) as any;
      if (response.code === 20000 && response.data) {
        const userData = response.data.records || [];
        setUsers(userData);
        setPagination({
          current,
          pageSize: size,
          total: response.data.total || userData.length,
        });
      } else {
        message.error("获取用户列表失败");
      }
    } catch (error) {
      console.error("加载用户列表失败:", error);
      message.error("获取用户列表失败");
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    loadUsers();
  }, []);



  // 处理搜索
  const handleSearch = (values: any) => {
    const params = {
      nickName: values.nickName?.trim() || undefined,
      phoneNumber: values.phoneNumber?.trim() || undefined,
      vipStatus: values.vipStatus,
    };
    setSearchParams(params);
    loadUsers(1, pagination.pageSize, params);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    loadUsers(1, pagination.pageSize);
  };

  const getMemberStatusTag = (vipStatus?: boolean, expiredDate?: string) => {
    if (vipStatus) {
      return (
        <Tag color="gold" icon={<CrownOutlined />}>
          VIP用户
        </Tag>
      );
    }
    return <Tag color="default">普通用户</Tag>;
  };

  const columns: ColumnsType<UserData> = [
    {
      title: "昵称",
      dataIndex: "nickName",
      key: "nickName",
    },
    {
      title: "手机号",
      dataIndex: "phoneNumber",
      key: "phoneNumber",
    },
    {
      title: "会员状态",
      key: "vipStatus",
      render: (_, record) =>
        getMemberStatusTag(record.vipStatus, record.expiredDate),
      filters: [
        { text: "VIP会员", value: true },
        { text: "普通用户", value: false },
      ],
      onFilter: (value, record) => record.vipStatus === value,
    },
    {
      title: "有效日期",
      dataIndex: "expiredDate",
      key: "expiredDate",
      render: (date: string) => {
        if (!date) return "-";
        const isExpired = dayjs(date).isBefore(dayjs(), 'day');
        return (
          <span style={{ color: isExpired ? "#ff4d4f" : "#52c41a" }}>
            {date}
          </span>
        );
      },
      sorter: (a, b) => {
        if (!a.expiredDate && !b.expiredDate) return 0;
        if (!a.expiredDate) return 1;
        if (!b.expiredDate) return -1;
        return dayjs(a.expiredDate).unix() - dayjs(b.expiredDate).unix();
      },
    },
    {
      title: "注册时间",
      dataIndex: "createdTime",
      key: "createdTime",
      sorter: (a, b) => {
        if (!a.createdTime || !b.createdTime) return 0;
        return dayjs(a.createdTime).unix() - dayjs(b.createdTime).unix();
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="default"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditMembership(record)}
          >
            设置会员
          </Button>
        </Space>
      ),
    },
  ];

  const handleView = (user: UserData) => {
    setSelectedUser(user);
    setIsViewModalVisible(true);
  };

  const handleEditMembership = (user: UserData) => {
    setSelectedUser(user);
    form.setFieldsValue({
      expiredDate: user.expiredDate ? dayjs(user.expiredDate) : null,
    });
    setIsEditModalVisible(true);
  };

  const handleViewModalCancel = () => {
    setIsViewModalVisible(false);
    setSelectedUser(null);
  };

  const handleEditModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (selectedUser && selectedUser.id) {
        setLoading(true);
        const expiredDate = values.expiredDate
          ? values.expiredDate.format("YYYY-MM-DD")
          : undefined;
        const vipStatus = !!expiredDate;

        const updateData: VidUser_ = {
          ...selectedUser,
          expiredDate,
          vipStatus,
        };

        const response = await AdminControllerService.userExpiredUsingPost(
          updateData
        );
        if (response.code === 20000) {
          message.success("设置成功");
          setIsEditModalVisible(false);
          form.resetFields();
          loadUsers(pagination.current, pagination.pageSize, searchParams);
        } else {
          message.error("设置失败");
        }
      }
    } catch (error) {
      console.error("设置会员失败:", error);
      message.error("设置失败");
    } finally {
      setLoading(false);
    }
  };

  const handleEditModalCancel = () => {
    setIsEditModalVisible(false);
    setSelectedUser(null);
    form.resetFields();
  };

  return (
    <Card title="用户管理">
      {/* 搜索表单 */}
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="nickName" label="昵称">
          <Input placeholder="请输入昵称" style={{ width: 150 }} />
        </Form.Item>
        <Form.Item name="phoneNumber" label="手机号">
          <Input placeholder="请输入手机号" style={{ width: 150 }} />
        </Form.Item>
        <Form.Item name="vipStatus" label="会员状态">
          <Select placeholder="请选择状态" style={{ width: 120 }} allowClear>
            <Select.Option value={true}>VIP会员</Select.Option>
            <Select.Option value={false}>普通用户</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={users}
        rowKey="id"
        loading={tableLoading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
          onChange: (page, size) => {
            loadUsers(page, size || pagination.pageSize, searchParams);
          },
          onShowSizeChange: (current, size) => {
            loadUsers(1, size, searchParams);
          },
        }}
      />

      {/* 查看用户详情模态框 */}
      <Modal
        title="用户详情"
        open={isViewModalVisible}
        onCancel={handleViewModalCancel}
        footer={[
          <Button key="close" onClick={handleViewModalCancel}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {selectedUser && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="昵称">
              {selectedUser.nickName || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">
              {selectedUser.phoneNumber || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="会员状态">
              {getMemberStatusTag(
                selectedUser.vipStatus,
                selectedUser.expiredDate
              )}
            </Descriptions.Item>
            <Descriptions.Item label="有效日期">
              {selectedUser.expiredDate || "无"}
            </Descriptions.Item>
            <Descriptions.Item label="注册时间">
              {selectedUser.createdTime || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {selectedUser.updatedTime || "-"}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 设置会员有效日期模态框 */}
      <Modal
        title="设置会员有效日期"
        open={isEditModalVisible}
        onOk={handleEditModalOk}
        onCancel={handleEditModalCancel}
        confirmLoading={loading}
        width={500}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="用户信息">
            {selectedUser && (
              <div>
                <p>
                  <strong>昵称：</strong>
                  {selectedUser.nickName || "-"}
                </p>
                <p>
                  <strong>手机号：</strong>
                  {selectedUser.phoneNumber || "-"}
                </p>
                <p>
                  <strong>当前状态：</strong>
                  {getMemberStatusTag(
                    selectedUser.vipStatus,
                    selectedUser.expiredDate
                  )}
                </p>
              </div>
            )}
          </Form.Item>

          <Form.Item
            name="expiredDate"
            label="会员有效日期"
            help="不设置日期则为普通用户，设置日期则自动成为VIP会员"
          >
            <DatePicker
              style={{ width: "100%" }}
              placeholder="请选择有效日期"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default UserManagement;
